<template>
  <div class="fc" style="height: 60px">
    <!-- <el-radio-group v-model:value="radio1">
            <el-radio value="huizhi" key="huizhi">绘制</el-radio>
            <el-radio value="shangchuan" key="shangchuan">上传</el-radio>
          </el-radio-group> -->

    <n-radio-group v-model:value="quyutype" name="radiobuttongroup1">
      <n-radio :key="'huizhi'" :value="'huizhi'" :label="'绘制'" />
      <n-radio :key="'shangchuan'" :value="'shangchuan'" :label="'上传'" />
      <n-radio :key="'zuobiao'" :value="'zuobiao'" :label="'坐标'" />
    </n-radio-group>
    <div class="fr">

      <div style="width: 150px;">

        <el-button-group v-if="quyutype == 'huizhi'">
          <el-button type="mini" @click="drawretangle">矩形</el-button>
          <el-button type="mini" @click="drawpolygon">多边形</el-button>
        </el-button-group>

        <!-- <div v-if="quyutype == 'huizhi'"> -->
        <!-- 文件上传 -->

        <el-upload
          class=""
          v-if="quyutype == 'shangchuan'"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="uploadFile"
        >
          <el-button type="" plain size=""> 矢量文件导入 </el-button>
        </el-upload>



        <el-popover
          placement="bottom"
          title="坐标输入参数"
          :width="400"
          trigger="hover"
          content="this is content, this is content, this is content"
        >
          <el-descriptions :column="1" border>
            <el-descriptions-item label="左上经度">
              <el-input style="width: 243px;" v-model="zuobiaoparams.zuojing" placeholder="" size="normal" clearable >
              </el-input>
              
            </el-descriptions-item>
            <el-descriptions-item label="左上纬度">
              <el-input style="width: 243px;" v-model="zuobiaoparams.zuowei" placeholder="" size="normal" clearable >
              </el-input>

            </el-descriptions-item>
            <el-descriptions-item label="右上经度">
              <el-input style="width: 243px;" v-model="zuobiaoparams.youjing" placeholder="" size="normal" clearable >
              </el-input>
            </el-descriptions-item>
            <el-descriptions-item label="右上纬度">
              <el-input style="width: 243px;" v-model="zuobiaoparams.youwei" placeholder="" size="normal" clearable >
              </el-input>
            </el-descriptions-item>
            <el-descriptions-item label="操作">
              <el-button type="primary" size="default" @click="zuobiaoOK">确定</el-button>
            </el-descriptions-item>
          </el-descriptions>

          <template #reference>
            <el-button-group v-if="quyutype == 'zuobiao'">
              <el-button type="mini" @click="drawretangle">输入坐标</el-button>
            </el-button-group>
          </template>
        </el-popover>

      </div>
      <div v-if="true">多边形个数：{{ props.fenfaparams.quyufanweival.length }}个</div>
      <el-button type="" size="default" @click="clearhuizhi()">清空</el-button>
    </div>

  </div>
</template>
<script setup>
import {
  defineProps,
  onMounted,
  defineEmits,
  ref,
  onUnmounted,
  defineExpose,
  reactive,
} from "vue";
import _ from "lodash";
import plot from "@/components/common/Earth/plot/plot.js";
import { makeStandardMapGrids } from "./useFenFu.js";
import { ElMessage } from "element-plus";


let zuobiaoparams = reactive({
  zuojing: '113.590326',
  zuowei: '34.8004289',
  youjing: '113.678152',
  youwei: '34.744600',
  // zuojing: '',
  // zuowei: '',
  // youjing: '',
  // youwei: '',
})

let props = defineProps({
  fenfaparams: Object,
});

let fengefangshitype = ref("不分割");
let quyutype = ref("huizhi");

let _layer = {};
let _p = {};

setTimeout(() => {
  let layer = new Cesium.CustomDataSource("plotlayer");
  viewer.dataSources.add(layer);
  _layer = layer;
  _p = new plot(viewer);
}, 1000);

let basejson = {
  type: "FeatureCollection",
  features: [],
};

function clearhuizhi() {
  props.fenfaparams.quyufanweival = [];
  reset();
} 

let tmpdatasource = ''

function zuobiaoOK(params) {
  // 跳转和格式化 上球
  // 校验格式
  // GEOJSON

  if (false) {
    ElMessage.error('输入数据有误')
    return
  }

  let itemd = {
    type: "Feature",
    properties: {},
    geometry: {
      coordinates: [[[]]],
      type: "MultiPolygon",
    },
  };

  itemd.geometry.coordinates[0][0].push([zuobiaoparams.zuojing, zuobiaoparams.zuowei]);
  itemd.geometry.coordinates[0][0].push([zuobiaoparams.zuojing, zuobiaoparams.youwei]);
  itemd.geometry.coordinates[0][0].push([zuobiaoparams.youjing, zuobiaoparams.youwei]);
  itemd.geometry.coordinates[0][0].push([zuobiaoparams.youjing, zuobiaoparams.zuowei]);
  itemd.geometry.coordinates[0][0].push([zuobiaoparams.zuojing, zuobiaoparams.zuowei]);
  
  let res = _.cloneDeep(basejson);
  res.features.push(itemd);
  props.fenfaparams.quyufanweival.push(res);
  addquyutomap(true);


}

function uploadFile(file) {
  let fileName = file.name;
  const reader = new FileReader();
  // 异步处理文件数据
  reader.readAsText(file.raw, "UTF-8");
  // 处理完成后立马触发 onload
  reader.onload = (fileReader) => {
    const fileData = fileReader.target.result;
    console.log(JSON.parse(fileData));

    let geojsondata = JSON.parse(fileData);

    // 判断是否为面并添加提示

    props.fenfaparams.quyufanweival.push(geojsondata);
    addquyutomap();

    // 渲染
    // Cesium.GeoJsonDataSource.load(geojsondata, {
    //   stroke: Cesium.Color.HOTPINK,
    //   fill: Cesium.Color.YELLOW.withAlpha(0.2),
    //   strokeWidth: 3,
    // }).then((res) => {
    //   tmpdatasource = res;
    //   viewer.dataSources.add(tmpdatasource);
    // });

    // viewer.flyTo(tmpdatasource);

    // console.log(JSON.parse(reader.result));
    // 上面的两个输出相同
    // JSON.parse(fileData) 就是读取到的内容，可在此进行文件处理
  };
}

function drawretangle() {
  reset();
  let itemd = {
    type: "Feature",
    properties: {},
    geometry: {
      coordinates: [[[]]],
      type: "MultiPolygon",
    },
  };
  _p.draw({
    type: "rectanglemark",
    c: async (e) => {
      let height = [];
      e.wgs84pos.map((item, index) => {
        // if (index != (e.wgs84pos.length - 1)) {
        itemd.geometry.coordinates[0][0].push([item.lng, item.lat]);
        height.push(item.alt);
        // }
      });
      itemd.geometry.coordinates[0][0].push([e.wgs84pos[0].lng, e.wgs84pos[0].lat]);
      height.push(e.wgs84pos[0].alt);
      // itemd.properties.height = height;

      let res = _.cloneDeep(basejson);
      res.features.push(itemd);

      props.fenfaparams.quyufanweival.push(res);
      addquyutomap();

      // 获取bbox
    },
  });
}

// 上传或者绘制之后

function addquyutomap(islocate = false) {
  reset();
  props.fenfaparams.quyufanweival.map((item1) => {
    item1.features.map((item) => {
      _layer.entities.add({
        polyline: {
          positions: new Cesium.CallbackProperty(function () {
            return Cesium.Cartesian3.fromDegreesArray(
              item.geometry.coordinates[0][0].flat()
            );
          }, false),
          // positions: Cesium.Cartesian3.fromDegreesArray(item.geometry.coordinates[0].flat()),
          // hierarchy: Cesium.Cartesian3.fromDegreesArray(item.geometry.coordinates[0].flat()),
          width: 3,
          material: Cesium.Color.RED.withAlpha(0.5),
        },
      });
      if (islocate) {
        viewer.flyTo(_layer,{
          duration: 0.5,
          offset: new Cesium.HeadingPitchRange(Cesium.Math.toRadians(-0), Cesium.Math.toRadians(-90.0), 100000),
        })
      }
    });
  });
}

function drawpolygon() {
  reset();
  let itemd = {
    type: "Feature",
    properties: {},
    geometry: {
      coordinates: [[[]]],
      type: "MultiPolygon",
    },
  };
  let polygon = [];
  _p.removeall();
  _p.draw({
    type: "polygonmark",
    c: async (e) => {
      // polygon = [];
      // e.wgs84pos.map((item, index) => {
      //   // if (index != (e.wgs84pos.length - 1)) {
      //   //   polygon.push(item.lng)
      //   //   polygon.push(item.lat)
      //   // }
      //   polygon.push(item.lng);
      //   polygon.push(item.lat);
      // });

      e.wgs84pos.map((item, index) => {
        // if (index != (e.wgs84pos.length - 1)) {
        itemd.geometry.coordinates[0][0].push([item.lng, item.lat]);
        // height.push(item.alt);
        // }
      });
      itemd.geometry.coordinates[0][0].push([e.wgs84pos[0].lng, e.wgs84pos[0].lat]);
      let res = _.cloneDeep(basejson);
      res.features.push(itemd);

      props.fenfaparams.quyufanweival.push(res);
      addquyutomap();


      // rangetype.value = 'ploygon'
      // 获取bbox
    },
  });
}

function reset() {
  _p.removeall();
  _layer.entities.removeAll();
}

onUnmounted(() => {
  reset()
})
</script>
<style lang="scss" scoped>
.fenfufangshiyixuanzediv {
  border-radius: 10px;
  background-color: #0ff2;
  padding: 0px 15px;
}
</style>
